package com.wteam.framework.modules.community.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wteam.framework.common.cache.impl.RedisCache;
import com.wteam.framework.common.enums.ResultCode;
import com.wteam.framework.common.enums.ResultUtil;
import com.wteam.framework.common.exception.ServiceException;
import com.wteam.framework.common.vo.PageVO;
import com.wteam.framework.common.vo.ResultMessage;
import com.wteam.framework.modules.community.dto.ModelMemberInfo;

import com.wteam.framework.modules.community.dto.SdRequestImgDto;
import com.wteam.framework.modules.community.dto.SdRequestTxtDto;
import com.wteam.framework.modules.community.entity.SdModel;
import com.wteam.framework.modules.community.mapper.SdModelMapper;
import com.wteam.framework.modules.community.service.SdModelService;
import com.wteam.framework.modules.member.entity.entity.SdMember;
import com.wteam.framework.modules.member.mapper.mapper.SdMemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * (SdModel)表服务实现类
 *
 * @author doncic
 * @since 2023-07-14 16:58:39
 */
@Service("sdModelService")
public class SdModelServiceImpl extends ServiceImpl<SdModelMapper, SdModel> implements SdModelService {

    @Autowired
    private SdModelMapper sdModelMapper;
    @Autowired
    private SdMemberMapper sdMemberMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResultMessage getAllModel() {
        //分页查询出所有的模型
        QueryWrapper<SdModel> wrapper = new QueryWrapper<>();
        PageVO pageVO = new PageVO();
        pageVO.setPageNumber(1);
        pageVO.setPageSize(20);
        Page<SdModel> modelPage = new Page<>(pageVO.getPageNumber(), pageVO.getPageSize());
        Page<SdModel> page = sdModelMapper.selectPage(modelPage, wrapper);
        return ResultUtil.data(page);
    }

    @Override
    public ResultMessage getModelDetails(String id) {
        LambdaQueryWrapper<SdModel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SdModel::getId, id);
        SdModel sdModels = sdModelMapper.selectOne(lambdaQueryWrapper);
        if (!ObjectUtil.isEmpty(sdModels)) {
            //获取模型对象中的memberId
            Long memberId = sdModels.getMemberId();
            LambdaQueryWrapper<SdMember> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SdMember::getId, memberId);
            List<SdMember> members = sdMemberMapper.selectList(queryWrapper);
            if (!ObjectUtil.isEmpty(members)) {
                SdMember sdMember = members.get(0);
                //创建一个自定义类，要包含模型和用户的信息
                ModelMemberInfo modelMemberInfo = new ModelMemberInfo();
                modelMemberInfo.setMember(sdMember);
                modelMemberInfo.setModel(sdModels);
                //返回包含这两类的对象
                return ResultUtil.data(modelMemberInfo);
            }
        }
        return ResultUtil.error(90010, "找不到该模型具体信息");
    }

    @Override
    public ResultMessage showModelByMember(Long id) {
        //先校验参数
        SdMember member = sdMemberMapper.selectById(id);
        if (ObjectUtil.isEmpty(member)) {
            return ResultUtil.error(ResultCode.NOT_CREATE_MEMBER);
        }
        //创建lambdaQueryWrapper对象
        LambdaQueryWrapper<SdModel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //条件查询
        lambdaQueryWrapper.eq(SdModel::getMemberId, member.getId());
        //创建分页对象
        Page<SdModel> page = new Page<>(1, 10);
        Page<SdModel> sdModelPage = sdModelMapper.selectPage(page, lambdaQueryWrapper);
        if (!ObjectUtil.isEmpty(sdModelPage)) {
            return ResultUtil.data(sdModelPage);
        }
        return ResultUtil.error(ResultCode.NOT_FIND_MEMBER_MODEL);
    }


    @Override
    public ResultMessage generateTxt2Img(Long id, SdRequestTxtDto sdRequestTxtDto) {
        // 参数校验 这里也可也使用Validation
        assert id != null : "id cannot be null";
        SdMember member = sdMemberMapper.selectById(id);
        if (member == null) {
            return ResultUtil.error(ResultCode.NOT_CREATE_MEMBER);
        }
        if (sdRequestTxtDto == null) {
            return ResultUtil.error(ResultCode.REQUEST_DTO_IS_BULL);
        }
        // 校验是否有生成图片的机会
        if (member.getPhotoCount() == 0) {
            return ResultUtil.error(ResultCode.ALREADY_NOT_CHANCE);
        }
        //将请求参数转化为json字符串
        String jsonStr = JSONUtil.toJsonStr(sdRequestTxtDto);
        //调用Stable Diffusion社区接口
        String apiUrl = "http://124.222.188.41:7861/sdapi/v1/txt2img";
        String apiKey = null;
        try {
            // 发起 POST 请求并处理响应
            HttpResponse response = HttpRequest.post(apiUrl)
                    .header("Authorization", "Bearer " + apiKey)
                    .contentType("application/json")
                    .body(jsonStr)
                    .execute();
            //解析响应数据
            int statusCode = response.getStatus();
            if (statusCode == 200) {
                //扣除对应用户的生成次数
                member.setPhotoCount(member.getPhotoCount() - 1);
                int insert = sdMemberMapper.insert(member);
                //响应成功
                String body = response.body();
                //解析响应的数据
                JSONObject entries = JSONUtil.parseObj(body);
                //获取image字段的信息
                JSONArray imagesBase64 = entries.getJSONArray("images");
                //将Base64 图片数据保存为文件
                //更新对应用户的图片生成次数
                return insert > 0 ? ResultUtil.data(imagesBase64) : ResultUtil.error(ResultCode.SD_API_ERROR);
            } else {
                //处理响应失败情况
                String errorMsg = response.body();
                errorMsg = errorMsg + statusCode;
                return ResultUtil.data(errorMsg);
            }
        } catch (Exception e) {
            return ResultUtil.data(ResultCode.SD_API_ERROR);
        }
    }

    @Override
    public ResultMessage generateImg2Img(SdRequestImgDto sdRequestImgDto) {
        //参数校验
        if (ObjectUtil.isEmpty(sdRequestImgDto)) {
            return ResultUtil.error(ResultCode.REQUEST_DTO_IS_BULL);
        }
        //将请求参数转化为json字符串
        String jsonStr = JSONUtil.toJsonStr(sdRequestImgDto);
        //调用Stable Diffusion社区接口
        String apiUrl = "http://124.222.188.41:7861/sdapi/v1/img2img";
        String apiKey = null;
        try {
            // 发起 POST 请求并处理响应
            HttpResponse response = HttpRequest.post(apiUrl)
                    .header("Authorization", "Bearer " + apiKey)
                    .contentType("application/json")
                    .body(jsonStr)
                    .execute();

            //解析响应数据
            int statusCode = response.getStatus();
            if (statusCode == 200) {
                //响应成功
                String body = response.body();
                //解析响应的数据
                JSONObject entries = JSONUtil.parseObj(body);
                //获取image字段的信息
                JSONArray imagesBase64 = entries.getJSONArray("images");
                //将Base64 图片数据保存为文件
                //这里先空
                return ResultUtil.data(imagesBase64);
            } else {
                //处理响应失败情况
                String errorMsg = response.body();
                errorMsg = errorMsg + statusCode;
                return ResultUtil.data(errorMsg);
            }
        } catch (Exception e) {
            return ResultUtil.data(ResultCode.SD_API_ERROR);
        }
    }

    @Override
    public ResultMessage uploadModel(SdModel sdModel) {
        //先校验参数非空
        if (ObjectUtil.isEmpty(sdModel)) {
            throw new ServiceException(ResultCode.REQUEST_DTO_IS_BULL);
        }
        //实现模型的上传
        int insert = sdModelMapper.insert(sdModel);
        return insert > 0 ? ResultUtil.success() : ResultUtil.error(ResultCode.ERROR);
    }

    @Override
    public ResultMessage deleteModel(Long id) {
        //先校验参数
        SdModel sdModel = sdModelMapper.selectById(id);
        if (ObjectUtil.isEmpty(sdModel)) {
            throw new ServiceException(ResultCode.REQUEST_DTO_IS_BULL);
        }
        // 创建一个 LambdaQueryWrapper 对象
        LambdaQueryWrapper<SdModel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 设置删除条件，根据主键字段 id 进行匹配
        lambdaQueryWrapper.eq(SdModel::getId, id);
        int affectedRows = sdModelMapper.delete(lambdaQueryWrapper);
        // 根据删除操作受影响的行数判断是否删除成功
        return affectedRows > 0
                ? ResultUtil.success()
                : ResultUtil.error(90017, "删除模型失败!");
    }

}
